package controllers

import (
	"net/http"
	"strconv"

	"github.com/dheisomgomes/codeapi/database"
	"github.com/dheisomgomes/codeapi/models"
	"github.com/gin-gonic/gin"
)

func Insert(c *gin.Context) {
	var code models.Code
	err := c.ShouldBindJSON(&code)
	if err != nil {
		c.JSON(http.StatusBadRequest, &gin.H{
			"error": "Error parsing data: " + err.Error(),
		})
		return
	}
	if code.Code == "" || code.Language == "" {
		c.JSON(http.StatusBadRequest, &gin.H{
			"error": "field code or language not informed",
		})
		return
	}
	db := database.GetDatabase()
	db.Create(&code)
	c.JSON(http.StatusOK, &code)
}

func ShowAll(c *gin.Context) {
	db := database.GetDatabase()
	var codes []models.Code
	err := db.Find(&codes).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, &gin.H{
			"error": "Internal error getting codes: " + err.Error(),
		})
		return
	}
	var result []gin.H
	for _, code := range codes {
		result = append(result, gin.H{
			"id":       code.ID,
			"title":    code.Title,
			"language": code.Language,
		})
	}
	c.JSON(http.StatusOK, &result)
}

func Show(c *gin.Context) {
	id := c.Param("id")
	db := database.GetDatabase()
	var code models.Code
	err := db.First(&code, id).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, &gin.H{
			"error": "Error getting code: " + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, &code)
}

func Delete(c *gin.Context) {
	id := c.Param("id")
	db := database.GetDatabase()
	err := db.Delete(&models.Code{}, id).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, &gin.H{
			"error": "Failed to delete code: " + err.Error(),
		})
		return
	}
	c.Status(http.StatusOK)
}

func Update(c *gin.Context) {
	id := c.Param("id")
	var code models.Code
	err := c.ShouldBindJSON(&code)
	if err != nil {
		c.JSON(http.StatusBadRequest, &gin.H{
			"error": "Error parsing data: " + err.Error(),
		})
		return
	}
	newID, err := strconv.Atoi(id)
	if err != nil {
		c.JSON(http.StatusBadRequest, &gin.H{
			"error": "Failed to parse integer id: " + err.Error(),
		})
		return
	}
	code.ID = uint(newID)
	db := database.GetDatabase()
	db.Save(&code)
	c.JSON(http.StatusOK, &code)
}
